package com.yang.job;

import com.yang.domain.entity.Article;
import com.yang.service.ArticleService;
import com.yang.utils.RedisCache;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.yang.constants.RedisConstants.ARTICLE_VIEWCOUNT;

@Component
public class UpdateViewCountJob {

    @Resource
    private RedisCache redisCache;

    @Resource
    private ArticleService articleService;


    @Scheduled(cron = "0/240 * * * * ?")
    public void updateViewCount(){
        //1.获取到redis里面的游览量
        Map<String, Integer> viewCountMap = redisCache.getCacheMap(ARTICLE_VIEWCOUNT);

        //2.map集合--->list<Article>集合
        List<Article> articles = viewCountMap.entrySet()
                .stream()
                .map(entry -> new Article(Long.valueOf(entry.getKey()), entry.getValue().longValue()))
                .collect(Collectors.toList());

        //3.更新到数据库
        articleService.updateBatchById(articles);
    }

}
